layui.use(['layer'], function () {
    let layer = layui.layer;
})
$(function () {
    // 页面初始化生成验证码
    window.onload = createCode('#loginCode');
    // 验证码切换
    $('#loginCode').click(function () {
        createCode('#loginCode');
    });
    // 登陆事件
    $('#loginBtn').click(function () {
        login();
    });
    // 注册事件
    $('#loginRegister').click(function () {
        register();
    });
    // 忘记密码事件
    $("#forgetBtn").click(function () {
        forget();
    })

    // 检测是否登录
    let token = localStorage.getItem("token");
    if (token == null)
        return false;

    $.ajax({
        url: "/user/myInfo",
        data: {
            "token": token
        },
        method: "GET",
        dataType: "json",
        success: function (result) {
            if (result.code === 200) {
                layer.confirm("检测到已经登录，是否跳转到首页？", {icon: 3, title: "提示"}, function (index) {
                    sessionStorage.setItem("myInfo_username", result.data.username);
                    sessionStorage.setItem("myInfo_headPortraitUrl", result.data.headPortraitUrl);
                    layer.close(index);
                    window.location.href = "/blog/index.html";
                })
            } else if (result.code === 401) {
                localStorage.removeItem("token");
                sessionStorage.clear();
                layer.msg("身份信息已经过期，请重新登录", {icon: 5});
            } else
                layer.msg(result.msg, {icon: 5});

        }
    })

});

// 生成验证码
function createCode(codeID) {
    var code = "";
    // 验证码长度
    var codeLength = 4;
    // 验证码dom元素
    var checkCode = $(codeID);
    // 验证码随机数
    var random = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for (var i = 0; i < codeLength; i++) {
        // 随机数索引
        var index = Math.floor(Math.random() * 36);
        code += random[index];
    }
    // 将生成的随机验证码赋值
    checkCode.val(code);
}

// 校验验证码、用户名、密码
function validateCode(inputID, codeID) {
    var inputCode = $(inputID).val().toUpperCase();
    var cardCode = $(codeID).val();
    var phone = $('#phone').val();
    var password = $('#password').val();
    if ($.trim(phone) == "" || $.trim(phone).length <= 0) {
        layer.alert("手机号不能为空");
        return false;
    }
    if ($.trim(password) == '' || $.trim(password).length <= 0) {
        layer.alert("密码不能为空");
        return false;
    }
    if (inputCode.length <= 0) {
        layer.alert("验证码不能为空");
        return false;
    }
    if (inputCode != cardCode) {
        layer.alert("请输入正确验证码");
        return false;
    }
    return true;
}

// 登录流程
function login() {
    if (!validateCode('#loginCard', '#loginCode')) {
        //阻断提示
    } else {
        let phone = $.trim($('#phone').val());
        let password = $.trim($('#password').val());
        let loginLoadIndex = layer.load(2);
        $('#loginBtn').val("正在登录...");
        $.ajax({
            url: window.location.protocol + '//' + window.location.host + '/user/login',
            method: 'post',
            data: {
                "phone": phone,
                "password": password
            },
            dataType: 'json',
            //contentType: 'application/json',
            success: function (result) {
                layer.close(loginLoadIndex);
                if (result.code === 200 || result.code === "200") {
                    layer.msg("登录成功", {icon: 1});
                    // 存放token
                    localStorage.setItem("token", result.token);
                    sessionStorage.setItem("myInfo_username", result.data.username);
                    sessionStorage.setItem("myInfo_headPortraitUrl", result.data.headPortraitUrl);

                    window.location.href = '/blog/index.html';
                } else {
                    layer.msg(result.msg, {icon: 5});
                    $('#loginBtn').val("登录");
                }

            },
            error: function () {
                layer.close(loginLoadIndex);
                layer.msg("登录失败", {icon: 5});
                $('#loginBtn').val("登录");
            }
        });
    }

}

// 注册流程
function register() {
    layer.open({
        type: '1',
        content: $('.registerPage'),
        title: '注册',
        area: ['400px', '500px'],
        btn: ['注册', '重置', '获取验证码'],
        closeBtn: '1',
        btn1: function (index, layero) {
            //注册回调
            let phone = $.trim($('#registerPhone').val());
            let email = $.trim($('#registerEmail').val());
            let password = $('#registerPassword').val();
            let code = $.trim($('#registerCode').val());
            let role_id = $('#role_id option:selected').val();
            if (!pattern_phone_email_password(phone, email, password))
                return false;//检验失败

            if (code === "") {
                layer.msg("请输入收到的验证码", {icon: 5});
                return false;
            }
            if (role_id === "") {
                layer.msg("请选择角色", {icon: 5});
                return false;
            }

            let registerLoadIndex = layer.load(2);
            $.ajax({
                method: 'post',
                url: window.location.protocol + '//' + window.location.host + '/user/register',
                dataType: 'json',
                data: {
                    "phone": phone,
                    "email": email,
                    "password": password,
                    "code": code,
                    "role_id": role_id
                },
                success: function (result) {
                    layer.close(registerLoadIndex);
                    if (result.code !== 200) {
                        layer.msg(result.msg, {icon: 5});
                        return false;
                    }
                    localStorage.setItem("token", result.token);
                    sessionStorage.setItem("myInfo_username", result.data.username);
                    sessionStorage.setItem("myInfo_headPortraitUrl", result.data.headPortraitUrl);
                    layer.msg(result.code + "：" + result.msg, {icon: 1, time: 500}, function () {
                        window.location.href = "/blog/index.html";
                    });
                },
                error: function () {
                    layer.close(registerLoadIndex);
                    layer.alert("请求超时！")
                    return false;//防止注册页面关闭
                }
            });
        },
        btn2: function (index, layero) {
            //重置回调
            document.getElementById("register_form").reset();
            // 防止注册页面关闭
            return false;
        },
        btn3: function (index, layero) {
            //发送验证码回调
            let email = $.trim($('#registerEmail').val());
            if (!pattern_phone_email_password("15088888888", email, "12345678"))
                return false;//校验失败
            let send_code_load_index = layer.load(0);
            $.get("/user/sendCode", {"email": email}, function (result) {
                layer.close(send_code_load_index);
                if (result.code !== 200) {
                    layer.msg(result.msg, {icon: 5});
                    return false;
                }
                layer.alert(result.msg, {icon: 1});
                $("#registerCode").prop("disabled",false).attr("placeholder","请输入验证码");
            })
            return false;
        },
        cancel: function (index, layero) {
            document.getElementById("register_form").reset();
            $("#register_layer").css("display", "none");
        },
        success: function (layero, index) {
            // $("#register_layer").removeClass("layui-hide");
        }
    })
}

// 忘记密码
function forget() {
    let layer = layui.layer;
    layer.open({
        type: '1',
        content: $('.forgetPage'),
        title: '重置密码',
        area: ['400px', '400px'],
        btn: ['确认', '获取验证码'],
        closeBtn: '1',
        btn1: function (index, layero) {
            //确认回调
            let phone = $.trim($('#forget_phone').val());
            let email = $.trim($("#forget_email").val());
            let password = $('#forget_password').val();
            let code = $.trim($('#forget_code').val());
            if (!pattern_phone_email_password(phone, email, password)) {
                return false;//检验失败
            }
            if (code === "") {
                layer.msg("请输入收到的验证码", {icon: 5});
                return false;
            }

            let forget_load_index = layer.load(2);
            $.ajax({
                method: 'post',
                url: window.location.protocol + '//' + window.location.host + '/user/forgetPassword',
                dataType: 'json',
                data: {
                    "phone": phone,
                    "email": email,
                    "password": password,
                    "code": code
                },
                success: function (result) {
                    layer.close(forget_load_index);
                    if (result.code !== 200) {
                        layer.msg(result.msg, {icon: 5});
                        return false;
                    }
                    localStorage.setItem("token", result.token);
                    sessionStorage.setItem("myInfo_username", result.data.username);
                    sessionStorage.setItem("myInfo_headPortraitUrl", result.data.headPortraitUrl);

                    layer.msg(result.code + "：" + result.msg, {icon: 1, time: 500}, function () {
                        window.location.href = "/blog/index.html";
                    });
                },
                error: function () {
                    layer.close(forget_load_index);
                    layer.alert("请求超时！")
                    return false;//防止注册页面关闭
                }
            });
            return false;
        },
        btn2: function (index, layero) {
            let phone = $.trim($('#forget_phone').val());
            let email = $.trim($("#forget_email").val());
            if (!pattern_phone_email_password(phone, email, "12345678")) {
                return false;//检验失败
            }
            let getCode_load_index = layer.load(2);
            $.ajax({
                method: 'get',
                url: window.location.protocol + '//' + window.location.host + '/user/forgetPassword',
                dataType: 'json',
                data: {
                    "phone": phone,
                    "email": email,
                },
                success: function (result) {
                    layer.close(getCode_load_index);
                    if (result.code !== 200) {
                        layer.msg(result.msg, {icon: 5});
                    } else {
                        layer.alert(result.msg, {icon: 1});
                        $("#forget_code").prop("disabled", false).attr("placeholder", "请输入收到的验证码");
                    }
                },
                error: function () {
                    layer.close(getCode_load_index);
                    layer.alert("请求超时！")
                }
            });
            // 防止页面关闭
            return false;
        },
        cancel: function (index, layero) {
            document.getElementById("forget_form").reset();
            $("#forget_layer").css("display", "none");
        },
        success: function (layero, index) {
            // $("#forget_layer").removeClass("layui-hide");
        }
    })
}

/**
 * 检验手机号邮箱和密码
 * @param phone 手机号
 * @param email 邮箱
 * @param password 密码
 * @returns {boolean}
 */
function pattern_phone_email_password(phone, email, password) {
    let phone_pattern = /^1(3[0-9]|8[0-9]|5[0-35-9]|9[0-35-9]|7[0-8]|4[0-14-9]|6[2567])[0-9]{8}$/;
    let email_pattern = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
    let password_pattern = /^.{8,}$/;
    if (!phone_pattern.test(phone)) {
        layer.msg("请输入正确的手机号", {icon: 5});
        return false;
    }
    if (!email_pattern.test(email)) {
        layer.msg("请输入正确的邮箱", {icon: 5});
        return false;
    }
    if (!password_pattern.test(password)) {
        layer.msg("密码至少8位", {icon: 5});
        return false;
    }
    return true;
}